package com.kaili.common.response;

import com.kaili.common.exception.IResponseStatus;
import com.kaili.common.util.CommonUtil;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Locale;

public class ResponseBodyWrapHandler implements HandlerMethodReturnValueHandler {

    private final HandlerMethodReturnValueHandler delegate;

    private MessageSource messageSource;

    public ResponseBodyWrapHandler(HandlerMethodReturnValueHandler delegate, MessageSource messageSource) {
        this.delegate = delegate;
        this.messageSource = messageSource;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return delegate.supportsReturnType(returnType);
    }

    @Override
    public void handleReturnValue(Object returnValue,
                                  MethodParameter returnType,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest) throws Exception {
        ResponseData responseData = null;
        if (returnValue instanceof RestStatus) {
            RestStatus restStatus = (RestStatus) returnValue;
            String msg = CommonUtil.getMessage(messageSource,restStatus.reasonPhrase());
            responseData = new ResponseData(restStatus.value(),msg);
        } else if(returnValue instanceof ResponseData) {
        	responseData = (ResponseData) returnValue;
            String msg = CommonUtil.getMessage(messageSource,responseData.getMessage());
            responseData.setMessage(msg);
        }else if(returnValue instanceof IResponseStatus) {
            IResponseStatus responseStatus = (IResponseStatus) returnValue;
            String msg = CommonUtil.getMessage(messageSource,responseStatus.getMsg());
            responseData = new ResponseData(responseStatus.getCode(),msg);
        }else{
            responseData = new ResponseData(returnValue, CommonStatus.OK);
        }
        delegate.handleReturnValue(responseData, returnType, mavContainer, webRequest);
    }
}